package com.rem.rabbitmq.boot.Dpriority;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @author Rem
 * @date 2021-12-30
 */

@Slf4j
@RestController
@RequestMapping("/priotiry")
@Api(tags = "优先级队列")
public class PriotiryController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ApiOperation(value = "发送一条的消息并且遍历")
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {

        for (int i = 0; i < 10; i++) {
            String msg = i + ":" + message;
            log.info("当前时间：{}，发送消息开始:{}", LocalDateTime.now(), msg);
            if (i % 3 == 0) {
                //给消息赋予一个priority属性
                Integer finalI = i;
                MessagePostProcessor messagePostProcessor = messageProperties -> {
                    messageProperties.getMessageProperties().setPriority(finalI);
                    return messageProperties;
                };
                rabbitTemplate.convertAndSend(PriotiryConfig.PRIOTIRY_EXCHANGE, PriotiryConfig.PRIOTIRY_ROUTING_KEY, msg, messagePostProcessor);
            } else {
                rabbitTemplate.convertAndSend(PriotiryConfig.PRIOTIRY_EXCHANGE, PriotiryConfig.PRIOTIRY_ROUTING_KEY, msg);
            }
            log.info("当前时间：{}，发送消息完毕:{}", LocalDateTime.now(), msg);
        }
    }


}
